/* eslint-disable no-param-reassign */
import DrawerFooter from '@/components/DrawerFooter';
import QR from '@/components/QR/QR';
import TauSimpleSelect from '@/components/TauSimpleSelect';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Input, ResponsiveGrid } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { ENUMS, FieldsGrid, TitleGrid, toSelectDataSource } from '../stores/definitions';

const FromItem = Form.Item;

function RuleForm({ channelId, modal, onSubmit, onCancel }) {
  const { channelStore: store } = useStore();
  const [channel] = useState(() => observable({}));
  const [QRModal, setQRModal] = useState({});
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  const isCompany = channel.independentAccount?.collectionAccountInformation?.type === 'MERCHANT_ID';
  const isPrice = channel.independentAccount?.independentAccountType === '1';

  // 重载definitions中的定义，处理一些根据上下文的动态定义
  const overrideModel = {
    independentAccount: {
      collectionAccountInformation: {
        name: {
          label: isCompany ? t`公司名称` : t`真实姓名`,
          ui: {
            itemProps: { required: isCompany },
          },
        },
        accountIdentification: {
          label: isCompany ? t`公司商户号` : t`账号标识`,
          ui: {
            renderer: (v) => (<Input
              value={v}
              readOnly={!isCompany}
              // disabled={!isCompany}
              placeholder={isCompany ? t`请填写公司商户号` : t`请扫码绑定收款帐号`}
              addonAfter={isCompany || isViewMode ? null : <Button type="primary" onClick={handleQrCode}>{t`扫码设置`}</Button>}
            />),
            itemProps: { required: isCompany },
          },
        },
      },
      acceptorType: {
        label: t`分账对象`,
        ui: {
          renderer: (v) => <TauSimpleSelect data={toSelectDataSource(ENUMS.acceptorType)} value={v} />,
          itemProps: { required: true },
        },
      },
      independentAccountType: {
        label: t`分账收款类型`,
        ui: {
          renderer: (v) => <TauSimpleSelect data={toSelectDataSource(ENUMS.independentAccountType)} value={v} />,
        },
      },
      independentAccountValue: {
        label: isPrice ? t`分账金额` : t`分账比例`,
        RMB: {
          label: isPrice ? t`分账金额` : t`分账比例`,
        },
      },
      viewAcceptorType: {
        label: t`分账对象`,
        ui: {
          renderer: (v) => <Input readOnly value={ENUMS.acceptorType[v]} />,
        },
      },
      viewIndependentAccountType: {
        label: t`分账收款类型`,
        ui: {
          renderer: (v) => <Input readOnly value={ENUMS.independentAccountType[v]} />,
        },
      },
      viewIndependentAccountValue: {
        label: isPrice ? t`分账金额` : t`分账比例`,
        RMB: {
          label: isPrice ? t`分账金额` : t`分账比例`,
          ui: {
            renderer: (v) => <Input readOnly value={v} />,
          },
        },
      },
    },
  };

  useEffect(() => {
    if (channelId) {
      (async () => {
        const data = await store.get(channelId);
        editCtx.origin = _.cloneDeep(data);
        _.assign(channel, data);
        const type = channel.independentAccount.acceptorType === '1' ? '0' : '1';
        _.set(channel, 'independentAccount.viewAcceptorType', type);
        _.set(channel, 'independentAccount.viewIndependentAccountType', channel.independentAccount?.independentAccountType);
        let price = '';
        if (channel.independentAccount.independentAccountType === '0') {
          price = 1 - Number(channel.independentAccount?.independentAccountValue?.RMB);
        } else {
          price = '剩余毛利';
        }
        _.set(channel, 'independentAccount.viewIndependentAccountValue.RMB', price);
      })();
    } else {
      _.set(channel, 'independentAccount.period', 0);
    }
  }, []);

  if (!channel) return <></>;

  // TODO 弹出二维码
  const handleQrCode = async () => {
    const { name } = channel;
    try {
      const baseUrl = await store.addProfitShare(channel);
      setQRModal({
        open: true,
        name,
        okText: '下载',
        onCancel: QROnCancel,
        baseUrl,
      });
    } catch (error) {
      console.log('二维码错误', error);
    }
  };

  const QROnCancel = () => {
    setQRModal({ open: false });
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(channel, name, value);
    // 联动效果可以在这里通过设置channel属性实现
    if (name === 'independentAccount.collectionAccountInformation.type') {
      _.unset(channel, 'independentAccount.collectionAccountInformation.name');
      _.unset(channel, 'independentAccount.collectionAccountInformation.accountIdentification');
    }
    if (name === 'independentAccount.acceptorType') {
      const type = (value === '1' ? '0' : '1');
      _.set(channel, 'independentAccount.viewAcceptorType', type);
    }
    if (name === 'independentAccount.independentAccountType') {
      _.set(channel, 'independentAccount.viewIndependentAccountType', value);
    }
    if (name === 'independentAccount.independentAccountValue.RMB') {
      let price = '';
      if (channel.independentAccount.independentAccountType === '0') {
        price = 1 - Number(value);
      } else {
        price = '剩余毛利';
      }
      _.set(channel, 'independentAccount.viewIndependentAccountValue.RMB', price);
    }

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
    // console.log('form data: ', name, value, toJS(channel));
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('...errors', errors);
      return;
    }
    onSubmit?.(channel);
  };

  return (
    <Form
      inline
      isPreview={isViewMode}
      {...formProps}
      value={channel}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`基本信息`} />
      <FieldsGrid
        formData={channel}
        mode={modal[0]}
        fields={['name', 'type', 'creditCode', 'address', 'mobile', 'appointCompanies']}
      />
      <TitleGrid title={t`分账信息`} />
      <FieldsGrid
        formData={channel}
        mode={modal[0]}
        fields={['period', 'suspensionOfDistribution'].map((n) => `independentAccount.${n}`)}
      />
      <FieldsGrid
        formData={channel}
        overrideModel={overrideModel}
        mode={modal[0]}
        fields={['type', 'name', 'accountIdentification'].map((n) => `independentAccount.collectionAccountInformation.${n}`)}
      />
      <FieldsGrid
        formData={channel}
        overrideModel={overrideModel}
        mode={modal[0]}
        fields={['acceptorType', 'independentAccountType', 'independentAccountValue.RMB'].map((n) => `independentAccount.${n}`)}
      />
      <FieldsGrid
        formData={channel}
        overrideModel={overrideModel}
        mode={modal[0]}
        fields={['viewAcceptorType', 'viewIndependentAccountType', 'viewIndependentAccountValue.RMB'].map((n) => `independentAccount.${n}`)}
      />
      <TitleGrid title={t`负责人信息`} />
      <FieldsGrid
        formData={channel}
        mode={modal[0]}
        fields={['principalName', 'certificateType', 'idNumber', 'principalMobile'].map((n) => `principalInfo.${n}`)}
      />
      <TitleGrid title={t`银行信息`} />
      <FieldsGrid
        formData={channel}
        mode={modal[0]}
        // columns={3}
        fields={['{RMB}.bank', '{RMB}.account', '{RMB}.accountName',
          '{HKD}.bank', '{HKD}.account', '{HKD}.accountName',
          '{MOP}.bank', '{MOP}.account', '{MOP}.accountName'].map((n) => `bankAccounts.${n}`)}
      />

      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>

      <QR modal={QRModal} />
    </Form>
  );
}

export default observer(RuleForm);

